from PySide6.QtWidgets import QWidget, QVBoxLayout, QHBoxLayout, QLabel, QSizePolicy
from PySide6.QtCore import Qt, QTimer
from PySide6.QtGui import QPixmap, QImage
import cv2
import numpy as np

from app.ui.utils import convert_cv_to_pixmap, format_class_counts

class VideoPanel(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        
    def setup_ui(self):
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(0, 0, 0, 0)  # 移除内边距，使视频最大化
        
        # 创建显示图像的标签
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)  # 允许标签拉伸填充
        self.image_label.setMinimumSize(640, 480)  # 设置最小尺寸
        main_layout.addWidget(self.image_label)
        
        # 创建统计信息显示区域
        stats_layout = QHBoxLayout()
        stats_layout.setContentsMargins(5, 0, 5, 0)  # 减小内边距
        
        # 统计信息标签
        self.stats_label = QLabel()
        self.stats_label.setStyleSheet("font-size: 14px;")
        stats_layout.addWidget(self.stats_label)
        
        # 类别计数标签
        self.class_counts_label = QLabel()
        self.class_counts_label.setStyleSheet("font-size: 14px;")
        stats_layout.addWidget(self.class_counts_label)
        
        main_layout.addLayout(stats_layout)
        
    def display_frame(self, frame):
        """显示处理后的视频帧"""
        if frame is None:
            return
            
        # 调整图像大小以适应标签
        height, width = frame.shape[:2]
        label_size = self.image_label.size()
        
        # 计算缩放比例
        scale = min(label_size.width() / width, label_size.height() / height)
        new_width = int(width * scale)
        new_height = int(height * scale)
        
        # 缩放图像
        frame = cv2.resize(frame, (new_width, new_height), interpolation=cv2.INTER_AREA)
        
        # 转换颜色空间从BGR到RGB
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        
        # 创建QImage
        image = QImage(frame.data, frame.shape[1], frame.shape[0], 
                      frame.strides[0], QImage.Format_RGB888)
        
        # 创建QPixmap并显示
        pixmap = QPixmap.fromImage(image)
        self.image_label.setPixmap(pixmap)
        
    def update_stats(self, total_objects, class_counts):
        """更新统计信息"""
        self.stats_label.setText(f"区域内出现的对象总数: {total_objects}")
        self.class_counts_label.setText(format_class_counts(class_counts))
        
    def set_status_message(self, message):
        """设置状态消息"""
        self.stats_label.setText(message)
